import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

public class Question6 extends JFrame {
    private JPanel contentPane;
    private JTable table;

    public static void main(String[] args) {
        Question6 frame = new Question6();
        frame.setVisible(true);
    }

    public Question6() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowActivated(WindowEvent e) {
                do_this_windowActivated(e);
            }
        });
        setTitle("表格练习");
        setBounds(100, 100, 500, 300);
        contentPane = new JPanel();
        //设置边框右上角标题
        Border titleBorder1 = BorderFactory.createTitledBorder("学生信息");
        contentPane.setBorder(titleBorder1);
        setContentPane(contentPane);
        //创建面板
        JScrollPane scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.CENTER);

        table = new JTable();
        table.setFont(new Font("宋体", Font.PLAIN, 14));
        table.setRowHeight(35);
        JTableHeader header = table.getTableHeader();
        header.setFont(new Font("宋体", Font.PLAIN, 16));
        header.setPreferredSize(new Dimension(header.getWidth(), 40));
        scrollPane.setViewportView(table);
        //设置表格数据居中
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, r);
    }

    //向表格中添加数据
    protected void do_this_windowActivated(WindowEvent e) {
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setRowCount(0);
        tableModel.setColumnIdentifiers(new Object[]{"姓名", "年龄", "专业"});
        tableModel.addRow(new Object[]{"张三", "23", "网络"});
        tableModel.addRow(new Object[]{"李四", "21", "测试"});
        table.setModel(tableModel);
        table.setAutoCreateRowSorter(true);
    }
}